package org.jeecg.modules.payment.custom.controller;

import cn.hutool.core.util.StrUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.payment.paymentalipaybankcode.entity.PaymentAlipayBankCode;
import org.jeecg.modules.payment.paymentalipaybankcode.service.IPaymentAlipayBankCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: 支付宝银行卡收款二维码配置
 * @Author: jeecg-boot
 * @Date: 2020-10-09
 * @Version: V1.0
 */
@Api(tags = "支付宝银行卡收款二维码配置")
@RestController("PaymentAlipayBankCodeController1")
@RequestMapping("/paymentalipaybankcode/paymentAlipayBankCode")
@Slf4j
public class PaymentAlipayBankCodeController extends JeecgController<PaymentAlipayBankCode, IPaymentAlipayBankCodeService> {
    @Autowired
    private IPaymentAlipayBankCodeService paymentAlipayBankCodeService;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 添加
     *
     * @param paymentAlipayBankCode
     * @return
     */
    @AutoLog(value = "支付宝银行卡收款二维码配置-添加")
    @ApiOperation(value = "支付宝银行卡收款二维码配置-添加", notes = "支付宝银行卡收款二维码配置-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody PaymentAlipayBankCode paymentAlipayBankCode, HttpServletRequest httpServerRequest) throws IOException, WriterException {
        //生成二维码图片
        String ewm = StrUtil.format("alipays://platformapi/startapp?appId=09999988&actionType=toCard&sourceId=bill&" +
                        "cardNo={}" +
                        "&bankAccount={}&" +
                        "money={}&" +
                        "amount={}&" +
                        "bankMark={}&" +
                        "bankName={}"
                , paymentAlipayBankCode.getCardNo()
                , paymentAlipayBankCode.getBankAccount(), paymentAlipayBankCode.getMoney(), paymentAlipayBankCode.getAmount(), paymentAlipayBankCode.getBankMark(), paymentAlipayBankCode.getBankName());
        //定义二维码的配置，使用HashMap
        Map hints = new ConcurrentHashMap();
        // 字符集，内容使用的编码
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        //容错等级，H、L、M、Q
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        //边距，二维码距离边的空白宽度
        hints.put(EncodeHintType.MARGIN, 0);
        //生成二维码对象，传入参数：内容、码的类型、宽高、配置
        BitMatrix bitMatrix = new MultiFormatWriter().encode(ewm, BarcodeFormat.QR_CODE, 100, 100, hints);
        //生成二维码，传入二维码对象、生成图片的格式、生成的路径
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "png", byteArrayOutputStream);
        Resource resource = new ByteArrayResource(byteArrayOutputStream.toByteArray()) {
            @Override
            public String getFilename() {
                return "tempp";
            }
        };
        HttpHeaders headers = new HttpHeaders();
        String token = httpServerRequest.getHeader("X-Access-Token");
        headers.add("X-Access-Token", token);
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> bodyParams = new LinkedMultiValueMap<>();
        bodyParams.add("file", resource);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyParams, headers);
        Map<String, Object> returnVo = restTemplate.postForObject("http://127.0.0.1:8080/jeecg-boot/sys/common/upload", requestEntity, Map.class);
        if ((boolean) returnVo.get("success")) {
            paymentAlipayBankCode.setPic((String) returnVo.get("message"));
            paymentAlipayBankCodeService.save(paymentAlipayBankCode);
            return Result.OK("添加成功！");
        }
        {
            return Result.error("图片上传失败");
        }


    }
    
}
